package sise.world.utils;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.AbstractMap.SimpleEntry;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.apache.log4j.Logger;

import sise.world.agent.AbstractAgent;
import sise.world.agent.AbstractAgent.AgentType;
import sise.world.map.Field.FieldType;

public class ImageHolder {

	private static final Logger logger = Logger.getLogger(ImageHolder.class);

	private final static ImageHolder singletonInstance = new ImageHolder();

	private HashMap<FieldType, BufferedImage> fieldTypeMap = new HashMap<FieldType, BufferedImage>();
	private HashMap<AgentType, BufferedImage> agentTypeMap = new HashMap<AgentType, BufferedImage>();
	private HashMap<Entry<FieldType, AgentType>, Icon> icons = new HashMap<Entry<FieldType, AgentType>, Icon>();

	private ImageHolder() {
		logger.info("Initializing ImageHolder singleton");
		for (FieldType fieldType : FieldType.values()) {
			try {
				BufferedImage backgroundImage = ImageIO.read(new File(this.getClass()
						.getResource(fieldType.getIconFilePath()).toURI()));
				fieldTypeMap.put(fieldType, backgroundImage);
			} catch (Exception e) {
				logger.error("Cannot retrieve icon for " + fieldType.name(), e);
			}
		}
		for (AgentType agentType : AgentType.values()) {
			try {
				BufferedImage agentImage = ImageIO.read(new File(this.getClass()
						.getResource(agentType.getIconFilePath()).toURI()));
				agentTypeMap.put(agentType, agentImage);
			} catch (Exception e) {
				logger.error("Cannot retrieve icon for " + agentType.name(), e);
			}
		}
		for (FieldType fieldType : FieldType.values()) {
			for (AgentType agentType : AgentType.values()) {
				BufferedImage result = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
				Graphics g = result.getGraphics();
				g.drawImage(fieldTypeMap.get(fieldType), 0, 0, null);
				g.drawImage(agentTypeMap.get(agentType), 0, 0, null);
				icons.put(new SimpleEntry<FieldType, AgentType>(fieldType, agentType), new ImageIcon(result));
			}
			BufferedImage result = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
			Graphics g = result.getGraphics();
			g.drawImage(fieldTypeMap.get(fieldType), 0, 0, null);
			icons.put(new SimpleEntry<FieldType, AgentType>(fieldType, null), new ImageIcon(result));
		}
	}

	public static ImageHolder getInstance() {
		return singletonInstance;
	}

	public Icon getIcon(FieldType fieldType, AbstractAgent agent) {
		if (agent == null) {
			return icons.get(new SimpleEntry<FieldType, AgentType>(fieldType, null));
		}
		return icons.get(new SimpleEntry<FieldType, AgentType>(fieldType, agent.getAgentType()));

	}
}
